<template>
  <div class="qrcodelogin">
    <template>
      <h1>二维码登录</h1>
      <div class="img">
        <img width="200px" height="200px" :src="qrimg" />
        <i
          class="mask"
          v-loading="false"
          v-show="showQrMask"
          :style="maskBg"
          @click="updataUrlFn"
        ></i>
      </div>
      <p>
        <svg aria-hidden="true" class="icon-wx">
          <use xlink:href="#icon-weixin"></use>
        </svg>
      </p>
      <h6>请使用手机微信扫描登录</h6>
    </template>
  </div>
</template>

<script>
import socketIo from "socket.io-client";

import qrcode from "qrcode";
import * as api from "@/api/login";

export default {
  data() {
    return {
      qrimg: "",
      showQrMask: false,
      maskBg: "",

      sid: "",
    };
  },
  created() {
    let io = socketIo("wss://chst.vip");
    io.on("connectSuccess", async ({ sid }) => {
      console.log("sid", sid);
      this.sid = sid;
      this.getQrcodeFn();
    });

    io.on("invalidCode", async (data) => {
      console.log(data);
      this.showQrMask = true;
      this.maskBg = {
        backgroundImage:
          "url(" + require("../../../assets/img/invalidQr.png") + ")",
      };
    });
    io.on("scancodeSuccess", async ({ state, wechatCode, msg }) => {
      console.log(state, wechatCode, msg);
      let rs = await api.weCatLogin(wechatCode);
      if (rs.data.state) {
        this.showQrMask = true;
        this.maskBg = {
          backgroundImage:
            "url(" + require("../../../assets/img/scancode.png") + ")",
        };
        alert("登录成功，跳转中。。。");
        setInterval(() => {
          this.jumpFn("/layout");
        }, 2000);
      }
      console.log(rs);
    });
  },
  methods: {
    async getQrcodeFn(sid) {
      let res = await api.getQrcodeUrl(this.sid);
      console.log("res", res);
      let { scanCodeUrl: qrcodeUrl } = res.data;

      qrcode.toDataURL(qrcodeUrl, (err, img) => {
        if (err) {
          throw err;
        }
        // console.log(img);
        this.qrimg = img;

        this.showQrMask = false;
      });
    },
    updataUrlFn() {
      console.log(this.sid);
      this.getQrcodeFn(this.sid);
    },
  },
};
</script>

<style lang="scss">
.qrcodelogin {
  position: relative;
}
.img {
  width: 200px;
  height: 200px;
  border: 1px solid wheat;
  margin: 0 auto;
}
.mask {
  width: 200px;
  height: 200px;
  opacity: 0.8;
  background-color: #fff;
  position: absolute;
  left: 80px;
  background-size: 50%;
  background-repeat: no-repeat;
  background-position: center;
  // background-image: url("../../../assets/img/invalidQr.png");
  cursor: pointer;
}
.icon-wx {
  height: 25px;
  width: 25px;
  position: absolute;
  left: 80px;
  bottom: -5px;
}
h6 {
  text-align: center;
  margin: 60px 0 0;
  color: wheat;
}
</style>
